#include "sync_check.h"
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>

Sync_Check::Sync_Check(Http_Get *parent) :
    Http_Get(parent),
    m_errout(0)
{

}

Sync_Check::~Sync_Check()
{

}

void Sync_Check::m_get(QString host, QString uin, QString sid,
					QString skey, QString deviceId, QStringList syncKey)
{
	QString ts = QString::number(time(NULL));
	QString url = host + WX_CGI_PATH + "synccheck?skey=" + skey +
		"&callback=jQuery183084135492448695_1420782130686&r=" + ts +
		"&sid=" + sid + "&uin=" + uin + "&deviceid=" + deviceId +
		"&synckey=";
	for (int i = 0; i < syncKey.size(); i++) {
		if (i != 0)
			url += "%7C";
		QStringList result = syncKey[i].split("|");
		url += result[0] + "_" + result[1];
	}
	url += "&_=" + ts;

#if QWX_DEBUG
	//qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << url;
#endif

	Http_Get::get(url, true);
}

void Sync_Check::getV2(QString uin, QString sid, QString skey, QString deviceId, QStringList syncKey)
{
	m_get("https://webpush2.weixin.qq.com", uin, sid, skey, deviceId, syncKey);
}

void Sync_Check::finished(QNetworkReply* reply)
{
	QString replyStr(reply->readAll());

	if (replyStr == "")
		return;

    //qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
    //qDebug() << "DEBUG:" << replyStr;
#if 0//QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
	qDebug() << "DEBUG:" << replyStr;
	QFile file("synccheck.json");
	if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		QTextStream out(&file);
		out << replyStr;
		file.close();
	}
#endif

    if (replyStr == "window.synccheck={retcode:\"0\",selector:\"0\"}") {
        m_errout = 0;

        Q_EMIT msg_state(false);
	}
	else {
        if(replyStr.startsWith("window.synccheck={retcode:\"")) {
            m_errout = 0;

            int size = sizeof("window.synccheck={retcode:\"")-1;
            int ret = atoi(replyStr.mid(size, 5).toStdString().c_str());
            if(ret != 0) {
                Q_EMIT error();
            }
            else {
                Q_EMIT msg_state(true);
            }
        }
        else {
            // 错误检测
            if(++m_errout > 10)
                Q_EMIT error();
            else
                Q_EMIT msg_state(false);
        }
	}
}

